//@Time : 2020/10/12 下午6:00
//@Author : bishisimo
package cmd

import (
	"context"
	"errors"
	"fmt"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"os"
	"strconv"
	"strings"
	"time"
	"uss-root/core"
	"uss-root/utils"
)

var rootCmd = &cobra.Command{
	Use:   "uss-root",
	Short: "启动uss的根因分析,指定websocket缓冲区大小",
	Long: `使用示例: 
1、uss-root（uss-root 0 *）
2、uss-root 1 k
`,
	Run: func(cmd *cobra.Command, args []string) {
		var num int
		var unit string
		if len(args) == 0 {
			num = 0
			unit = "b"
		} else if len(args) == 2 {
			a1, err := strconv.Atoi(args[0])
			if err != nil {
				utils.HandleErr(err)
				_ = cmd.Help()
				return
			}
			num = a1
			unit = strings.ToLower(args[1])
		} else {
			_ = cmd.Help()
		}
		switch unit {
		case "b":
			viper.Set("size", num)
		case "k":
			viper.Set("size", num*1024)
		case "m":
			viper.Set("size", num*1024*1024)
		case "g":
			viper.Set("size", num*1024*1024*1024)
		default:
			utils.HandleErr(errors.New("can not support so unit"))
			return
		}
		utils.Logger.Info().Int("buffer size:", viper.GetInt("size")).Send()
		core.NewUpgrader()
		influx := core.NewInfluxClient()
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		sc := core.GenerateSysStream(ctx, 2*time.Second)
		go influx.WriteSysStream(ctx, sc)
		_ = core.GinServerStart()
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println("cmd error")
		os.Exit(1)
	}
}
